package net.huashitong.user.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sirdc.modules.core.config.Global;
import com.sirdc.modules.sys.entity.SysFile;
import com.sirdc.modules.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysPicture;
import com.sirdc.modules.sys.service.SysFileService;
import com.sirdc.modules.sys.service.SysPictureService;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 批量上传文件
 * @author lzr
 *
 */
@Controller
@RequestMapping("/pictureUpload")
public class PictureUploadController extends JsonBaseController {

	@Autowired
	private SysPictureService sysPictureService;
	@Autowired
	private SysFileService sysFileService;
	@Override
	protected String getView(String arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@ResponseBody
	@RequestMapping("/uploadBatch")
	public Message uploadBatch(@RequestParam MultipartFile[] files) throws Exception {
		if (files == null || files.length==0) {
			return coverMessage("500", "上传文件为空");
		}
		List<Map<String, Object>> maps = new ArrayList<Map<String,Object>>(); 
		for (MultipartFile multipartFile : files) {
//			SysPicture sysPicture = new SysPicture();
//			sysPictureService.savePicture(sysPicture, multipartFile);
			SysFile sysFile = new SysFile();
			sysFileService.saveFile(sysFile,multipartFile);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("sysId", sysFile.getSysId());
			maps.add(map);
		}
		
		return coverMessage("200", "上传文件成功", maps);
	}

	@RequestMapping(value = "/download")
	public void downLoad(String id, HttpServletRequest req, HttpServletResponse resp,String name) throws Exception {
		downLoadFileId(id, req, resp,name);
	}



	public void downLoadFileId(String fileId, HttpServletRequest req, HttpServletResponse resp, String name) throws Exception {
		if (StringUtils.isBlank(fileId)){
			logger.error("请求的文件不存在");
		}
		SysFile sysFile = sysFileService.getById(fileId);

		if (StringUtils.isBlank(name)){
			name=sysFile.getFilename()+"."+sysFile.getFileType();
		}
		String encode = URLEncoder.encode(name, "UTF-8");
		if (sysFile == null) {
			throw new Exception(" current request path is empty");
		}
		String filepath = sysFile.getUrl();
		int index = filepath.lastIndexOf(Global.USER_DIR);
		if (index >= 0) {
			filepath = filepath.substring(index + Global.USER_DIR.length());

		}
		try {
			filepath = UriUtils.decode(filepath, "UTF-8");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
		}
		File file = new File(Global.getUploadBaseDir() + filepath);
		resp.reset();
		InputStream inputStream = new FileInputStream(file);
		try {

			/*resp.setHeader("Content-Type", "application/x-download");
			resp.setHeader("Content-Disposition", "attachment; filename=" + encode);*/
			FileCopyUtils.copy(inputStream, resp.getOutputStream());


			return;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new FileNotFoundException("请求的文件不存在");
		}finally {
			inputStream.close();
		}


	}
}
